package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;

public class ServerManager {
	private int port;
	private ServerSocket serverSocket;
	volatile boolean listening;
	private ThreadGroup sockets;
	
	public ServerManager(int port) {
		this.port = port;
		this.serverSocket = null;
		this.listening = true;
		this.sockets = new ThreadGroup("sockets");
	}
	
	public void shutdown() {
		if (!listening) {
			System.out.println("Shutdown already called");
		} else {
			System.out.println("Shutdown has been called");
			listening = false;
		}
		
		Thread[] threadArray = new Thread[sockets.activeCount()];
		sockets.enumerate(threadArray);
		for (int x=0;x<threadArray.length;x++) {
			((ServerThread) threadArray[x]).kill();
		}
	}
	
	public void fireItUp() throws IOException {
        try {
            serverSocket = new ServerSocket(port);
            serverSocket.setSoTimeout(1000);
            System.out.println("Now listening on port "+port);
        } catch (IOException e) {
            System.err.println("Could not listen on port: "+port);
            System.exit(-1);
        }

        
        while (listening) {
        	try {
        		new ServerThread(serverSocket.accept(), this, sockets);
        	} catch (SocketTimeoutException e) {
        		
        	}
        }

        serverSocket.close();
	}
	
	public void printToThreads(String text) {
		Thread[] threadArray = new Thread[sockets.activeCount()];
		sockets.enumerate(threadArray);
		for (int x=0;x<threadArray.length;x++) {
			((ServerThread) threadArray[x]).printExternal(text);
		}
	}
	
	public String getWelcomeMessage() {
		return "You are now connected on port "+port;
	}
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		ServerManager manager = new ServerManager(80);
		manager.fireItUp();
	}
}
